package com.typhoon.spring_shiro.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.typhoon.spring_shiro.dto.PermissionAppDto;
import com.typhoon.spring_shiro.dto.PermissionDto;
import com.typhoon.spring_shiro.dto.RoleDto;
import com.typhoon.spring_shiro.dto.UserDto;
import com.typhoon.spring_shiro.service.PermissionAppService;
import com.typhoon.spring_shiro.service.PermissionService;
import com.typhoon.spring_shiro.service.RoleService;
import com.typhoon.spring_shiro.service.UserService;
import com.typhoon.spring_shiro.utils.CollectionUtils;
import com.typhoon.spring_shiro.utils.CommonUtils;
import com.typhoon.spring_shiro.utils.SessionUtils;
import com.typhoon.spring_shiro.utils.limit.RateLimiter;
import com.typhoon.spring_shiro.vo.UserLoginVo;

/**
 * 用户controller
 * 
 * @author Typhoon
 * @date 2017-05-26 11:01
 * @since V2.0
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Resource
	private UserService userService;
	
	@Resource
	private RoleService roleService;
	
	@Resource
	private PermissionService permissionService;
	
	@Resource
	PermissionAppService permissionAppService;

	@RequestMapping(value = "/get-user.do")
	@RequiresRoles("frontDest")
	public void queryUser(HttpServletRequest request, HttpServletResponse response) {
		Long id = CommonUtils.evalLong(request.getParameter("id"));
		Assert.state(id > 0);
		try {
			UserDto user = userService.queryByPK(id);
			if (null == user) {
				this.putFailtResult(response, "查询为空");
				return;
			}
			this.putSuccessResult(response, user);
		} catch (Exception e) {
			logger.error("查询异常", e);
			this.putFailtResult(response, "查询异常");
		}
	}

	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public void login(HttpServletRequest request, @RequestBody UserLoginVo loginVo, HttpServletResponse response) {

		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getName(), loginVo.getPassword());
		try {
			
			if(!"aeolus".equals(loginVo.getName())) {
				this.putFailtResult(response,"登录失败");
				return;
			}
			//TODO 自定义登录方式
			subject.login(token);
			
			List<PermissionAppDto> apps = SessionUtils.getApps();
			this.putSuccessResult(response,"登录授权成功",apps);
		} catch (Exception e) {
			logger.error("",e);
			this.putFailtResult(response,"登录异常");
		}

	}

	/**
	 * 初始化一些东西
	 * 
	 * @author Typhoon
	 * @date 2017-05-26 11:00
	 * @param loginVo
	 */
	private void init(UserLoginVo loginVo) {
		logger.info("need do something with loginVo...-{}",JSONObject.toJSONString(loginVo, new SerializerFeature[0]));

	}
	
	@RequestMapping(value = "/roles.do")
	public void queryRolesByUser(@RequestBody Map<String,Object> requestParam,HttpServletRequest request,HttpServletResponse response) {
		
		Long userId = CommonUtils.evalLong(requestParam.get("userId"));
		if(userId < 0) {
			logger.warn("查询角色信息参数异常,userId:{}",userId);
			this.putFailtResult(response,"参数非法");
			return;
		}
		boolean rs = RateLimiter.tryAccess("aaa", 30, 2);
		if(!rs) {
			this.putFailtResult(response,"访问超过限制次数");
			return;
		}
		try {
			List<RoleDto> roles = roleService.listAllByUserId(userId);
			logger.info("roles:{}",JSON.toJSONString(roles));
			this.putSuccessResult(response,roles);
		} catch (Exception e) {
			logger.error("查询角色信息异常",e);
			this.putFailtResult(response,"查询角色信息异常");
		}
	}
	
	@RequestMapping(value = "/permissions.do")
	public void queryPermissionsByRoles(@RequestBody List<RoleDto> roles,HttpServletResponse response) {
		if(CollectionUtils.isEmpty(roles)) {
			this.putFailtResult(response,"角色信息为空");
			return;
		}
		try {
			List<PermissionDto>  permissions = permissionService.listAllPermission(roles);
			logger.info("根据角色查询权限信息-{}",JSON.toJSONString(permissions));
			this.putSuccessResult(response,permissions);
		} catch (Exception e) {
			logger.error("查询异常",e);
			this.putFailtResult(response,"查询异常");
		}
	}
	
	@RequestMapping(value = "/apps.do")
	public void queryAppsByPermissons(@RequestBody List<PermissionDto> permissions,HttpServletResponse response) {
		if(CollectionUtils.isEmpty(permissions)) {
			this.putFailtResult(response,"权限信息为空");
			return;
		}
		try {
			List<PermissionAppDto> apps = permissionAppService.listAllByPermissions(permissions);
			logger.info("查询权限应用信息-{}",JSON.toJSONString(apps));
			this.putSuccessResult(response,apps);
		} catch (Exception e) {
			logger.error("查询应用信息失败",e);
			this.putFailtResult(response,"查询应用信息异常");
		}
	}
	
	@RequestMapping(value = "/app-sale.do")
	@RequiresPermissions(value="sale",logical = Logical.AND)
	public void showSale(@RequestBody Map<String,Object> requestParam,HttpServletResponse response) {
		String saleCode = CommonUtils.evalString(requestParam.get("saleCode"));
		if(StringUtils.isEmpty(saleCode)) {
			this.putFailtResult(response,"销售子系统权限编码为空");
			return;
		}
		try {
			requestParam.clear();
			requestParam.put("permissionCode", saleCode);
			PermissionAppDto  app =	permissionAppService.get(requestParam);
			if(null == app){
				this.putFailtResult(response,"销售子系统不存在");
				return;
			}
			this.putSuccessResult(response, app);
		} catch (Exception e) {
			logger.error("进入销售子系统异常",e);
			this.putFailtResult(response, "进入销售子系统有异常");
		}
	}
	
	@RequestMapping(value = "/app-finance.do")
	@RequiresPermissions("financial")
	//finance
	public void showFinance(@RequestBody Map<String,Object> requestParam,HttpServletResponse response) {
		String financeCode = CommonUtils.evalString(requestParam.get("financeCode"));
		if(StringUtils.isEmpty(financeCode)) {
			this.putFailtResult(response,"财务子系统权限编码为空");
			return;
		}
		try {
			requestParam.clear();
			requestParam.put("permissionCode", financeCode);
			PermissionAppDto  app =	permissionAppService.get(requestParam);
			if(null == app){
				this.putFailtResult(response,"财务子系统不存在");
				return;
			}
			this.putSuccessResult(response, app);
		} catch (Exception e) {
			logger.error("进入财务子系统异常",e);
			this.putFailtResult(response, "进入财务子系统有异常");
		}
	}

}
